package com.start.common.mybaitsplus;

import com.alibaba.fastjson2.JSONObject;
import com.start.common.entity.StartBaseEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes(value = {JdbcType.VARCHAR, JdbcType.NVARCHAR, JdbcType.LONGVARCHAR})
public class StartMyBaitsEntityHandler extends BaseTypeHandler<StartBaseEntity> {

    private Class<? extends StartBaseEntity> clazz;

    public StartMyBaitsEntityHandler(Class<? extends StartBaseEntity> clazz) {
        this.clazz = clazz;
    }


    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, StartBaseEntity entity, JdbcType jdbcType) throws SQLException {
        if (entity == null) return;
        String json = JSONObject.toJSONString(entity);
        preparedStatement.setString(i, json);
    }

    @Override
    public StartBaseEntity getNullableResult(ResultSet resultSet, String s) throws SQLException {
        if (resultSet == null) return null;
        if (StringUtils.isEmpty(s)) return null;
        return JSONObject.parseObject(s, clazz);
    }

    @Override
    public StartBaseEntity getNullableResult(ResultSet resultSet, int i) throws SQLException {
        if (resultSet == null) return null;
        String string = resultSet.getString(i);
        if (StringUtils.isEmpty(string)) return null;
        return JSONObject.parseObject(string, clazz);
    }

    @Override
    public StartBaseEntity getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        if (callableStatement == null) return null;
        String string = callableStatement.getString(i);
        if (StringUtils.isEmpty(string)) return null;
        return JSONObject.parseObject(string, clazz);
    }
}
